package com.jvmoutofmemory.octopus.ui;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class OctopusManagerPanel extends JPanel {

    private MainOctopusFrame mainOctopusFrame;

    private JTable filesInfoTable;
    private JScrollPane fileInfoScollPane;
    private OctopusTableModel tableModel;
    private OctopusTablePopMenu tablePopMenu;

    public OctopusManagerPanel(MainOctopusFrame mainOctopusFrame) {
        this.mainOctopusFrame = mainOctopusFrame;
    }

    public void initialize() {
        this.setLayout(new BorderLayout());

        tablePopMenu = new OctopusTablePopMenu(mainOctopusFrame);
        tablePopMenu.initialize();

        tableModel = new OctopusTableModel();
        tableModel.initialize();

        filesInfoTable = new JTable(tableModel);
        filesInfoTable.setRowHeight(30);
        filesInfoTable.getColumnModel().getColumn(0).setPreferredWidth(400);
        filesInfoTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON3) {
                    int[] selectedRows = filesInfoTable.getSelectedRows();
                    if (selectedRows == null || selectedRows.length == 0) {
                        int rowIndex = filesInfoTable.rowAtPoint(e.getPoint());
                        if (rowIndex == -1) {
                            return;
                        }

                        filesInfoTable.setRowSelectionInterval(rowIndex, rowIndex);
                    }

                    tablePopMenu.show(filesInfoTable, e.getX(), e.getY());
                }
            }
        });

        fileInfoScollPane = new JScrollPane(filesInfoTable);
        this.add(fileInfoScollPane, BorderLayout.CENTER);
    }

    public OctopusTableModel getTableModel() {
        return tableModel;
    }

    public void renderTableData() {
        tableModel.sort();
        filesInfoTable.updateUI();
        filesInfoTable.repaint();
    }

    public JTable getFilesInfoTable() {
        return filesInfoTable;
    }
}
